package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.response.ProductUnitInfoVO;
import com.wing.product.service.ProductUnitService;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.OrderForm;
import com.wing.sell.model.response.*;
import com.wing.sell.service.*;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-试产销售订单表管理", tags = "#/sell/trialOrder")
@RestController("trialOrderController")
@RequestMapping("sell/admin/trialOrder")
@RequiredArgsConstructor
@Slf4j
public class TrialOrderController {

    private final OrderService orderService;
    private final OrderProService orderProService;
    private final CustomersInfoService customersInfoService;
    private final ContactInfoService contactInfoService;
    private final AgentService agentService;
    private final OrderProReviewService orderProReviewService;
    private final OrderProEnclosureService orderProEnclosureService;
    private final OrderReviewProcessService orderReviewProcessService;
    private final ProductUnitService productUnitService;

    @ApiOperation(value = "查询所有销售订单表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "desc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OrderVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,String code
            ,Order.Status status
            ,Order.OrderSource orderSource
            ,String customerName
    ){

        Page<OrderVO> pg = new Page<>(page, limit);

        //排序
        Map params=new HashMap();
        params.put("sort",StrUtil.toUnderlineCase(sort));
        params.put("order",StrUtil.toUnderlineCase(order));

        //搜索
        if (StringUtils.isNotBlank(code)) {
            params.put("code", code);
        }
        if (status!=null) {
            params.put("status", status.getValue());
        }
        if (orderSource!=null) {
            params.put("orderSource", orderSource.getValue());
        }
        if (StringUtils.isNotBlank(customerName)) {
            List<CustomersInfo> customersInfoList = customersInfoService.list(new QueryWrapper<CustomersInfo>().like("customer_name",customerName));
            List listIds = new ArrayList();
            for (int i = 0;i<customersInfoList.size();i++){
                listIds.add(customersInfoList.get(i).getId());
            }
            params.put("listIds", listIds);
        }
        params.put("orderType", Order.OrderType.trial.getValue());
        //询价订单页面显示 订单状态:pending(0,待提交);accept(1,待受理);review(2,待评审);refuse(3,不接单);offer(4,待报价);tosign(5,待签约);signed(6,已签约);finish(7,完成,签约后的结案后的状态);over(8,关闭,未签约的结案后状态)
        params.put("show",new ArrayList<Integer>(){{add(6);add(7);}});
        IPage<OrderVO> list = orderService.pageList4app(pg,params);

        list.getRecords().parallelStream().forEach(k -> {
            /*//订单关联报价单
            QueryWrapper<OrderOffer> offerQueryWrapper = new QueryWrapper<>();
            List<OrderOffer> orderOfferList = orderOfferService.list(offerQueryWrapper.eq("order_id",k.getId()));
            //报价单关联明细
            orderOfferList.parallelStream().forEach(h -> {
                QueryWrapper<OrderOfferDetail> offerDetailQueryWrapper = new QueryWrapper<>();
                h.setOrderOfferDetailList(orderOfferDetailService.list(offerDetailQueryWrapper.eq("offer_id",h.getId())));
            });
            //订单包含报价单
            k.setOrderOfferList(orderOfferList);*/
            //包含产品  关联评审记录 关联附件
            QueryWrapper<OrderPro> proQueryWrapper = new QueryWrapper<>();
            proQueryWrapper.eq("order_id",k.getId());
            //只评审 受理的产品
            /*if (k.getStatus()==Order.Status.review){
                proQueryWrapper.eq("status", OrderPro.Status.accepted);
            }
            //只报价 终审通过的产品 后续展示也是
            if (k.getStatus()==Order.Status.offer||k.getStatus()==Order.Status.tosign||k.getStatus()==Order.Status.signed||k.getStatus()==Order.Status.finish){
                proQueryWrapper.eq("final_result", OrderPro.FinalResult.pass);
            }*/
            List<OrderPro> proList=orderProService.list(proQueryWrapper);
            proList.parallelStream().forEach(z -> {
                //产品关联评审记录
                QueryWrapper<OrderProReview> wrapper = new QueryWrapper<>();
                List<OrderProReview> orderProReviewList = orderProReviewService.list(wrapper.eq("pro_id",z.getId()));
                orderProReviewList.parallelStream().forEach(h -> {
                    OrderReviewProcessVO appById = orderReviewProcessService.get4appById(h.getReviewProcessId());
                    if (ObjectUtil.isNotEmpty(appById)) {
                        h.setReviewProcessName(appById.getName());
                    }
                });
                z.setOrderProReviewList(orderProReviewList);
                //产品关联附件
                QueryWrapper<OrderProEnclosure> query = new QueryWrapper<>();
                z.setOrderProEnclosureList(orderProEnclosureService.list(query.eq("pro_id",z.getId())));
                ProductUnitInfoVO appById = productUnitService.get4appById(z.getProUnitId());
                if (ObjectUtil.isNotEmpty(appById)) {
                    z.setProUnitName(appById.getName());
                }
            });
            //包含产品
            k.setOrderProList(proList);
            //客户公司名称
            CustomersInfoVO service4appById = customersInfoService.get4appById(k.getCustomerId());
            if (ObjectUtil.isNotEmpty(service4appById)) {
                k.setCustomerName(service4appById.getCustomerName());
            }
            //联系人名称
            ContactInfoVO appById = contactInfoService.get4appById(k.getCustomerContactsId());
            if (ObjectUtil.isNotEmpty(appById)) {
                //联系人电话
                k.setCustomerContactsName(appById.getName());
                k.setCustomerContactsPhone(appById.getTelephone());
            }
            //渠道名称
            if (k.getChannelId()==null){//非渠道订单 渠道ID为空
                k.setChannelName("非渠道订单");
            }else{
                AgentVO byId = agentService.get4appById(k.getChannelId());
                if (ObjectUtil.isNotEmpty(byId)) {
                    k.setChannelName(byId.getName());
                }
            }
        });

        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加销售订单表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(OrderForm.Add.class) @RequestBody OrderForm orderForm) {
        try{
            orderService.addFormal(orderForm);
            return JsonResult.success("添加成功");
        }catch(Exception e){
            log.error("添加失败:", e);
            return JsonResult.fail("添加失败"+e.getMessage());
        }
    }



    @ApiOperation(value = "修改销售订单表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(OrderForm.Update.class) OrderForm orderForm) {
        Order order = orderService.getById(orderForm.getId());
        if(order == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(Order.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderForm, order, copyOptions);
        if (orderService.updateById(order)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除销售订单表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "销售订单表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long orderId) {
        if (orderService.removeById(orderId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
}
